<template>
    <div>
      <div class="icon">
          <img src="../../assets/account.jpg" />
        </div>
      <a-form-model ref="form" :model="model" :rules="validatorRules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item required prop="username" label="用户名">
          <a-input v-model="model.username" size="large" placeholder="请输入帐户名">
            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
          </a-input>
        </a-form-model-item>
        <a-form-model-item required prop="password" label="密    码">
          <a-input v-model="model.password" size="large" type="password" autocomplete="false" placeholder="请输入密码" v-if="!eysShow">
            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
          </a-input>
          <a-input v-model="model.password" size="large" type="text" autocomplete="false" placeholder="请输入密码"  v-if="eysShow">
            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
          </a-input>
          <i class="iconfont icon-yanjing" @click="openPass" v-if="eysShow"></i>
          <i class="iconfont icon-yanjing1" @click="openPass"  v-if="!eysShow"></i>
        </a-form-model-item>
<!-- 
        <a-row :gutter="0">
          <a-col :span="16">
            <a-form-model-item required prop="inputCode">
              <a-input v-model="model.inputCode" size="large" type="text" placeholder="请输入验证码">
                <a-icon slot="prefix" type="smile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" style="text-align: right">
            <img v-if="requestCodeSuccess" style="margin-top: 2px;" :src="randCodeImage" @click="handleChangeCheckCode"/>
            <img v-else style="margin-top: 2px;" src="../../assets/checkcode.png" @click="handleChangeCheckCode"/>
          </a-col>
        </a-row> -->
      </a-form-model>
    </div>
</template>

<script>
  import { getAction } from '@/api/manage'
  import { mapActions,mapGetters } from 'vuex'

  export default {
    name: 'LoginAccount',
    data(){
      return {
        requestCodeSuccess: false,
        randCodeImage: '',
        currdatetime: '',
        loginType: 0,
        eysShow:false,
        model:{
          username: '',
          password: '',
          // inputCode: ''
        },
        validatorRules:{
          username: [
            { required: true, message: '请输入用户名!' },
            { validator: this.handleUsernameOrEmail }
          ],
          password: [{
            required: true, message: '请输入密码!', validator: 'click'
          }],
          // inputCode: [{
          //   required: true, message: '请输入验证码!'
          // }]
        }
        ,
        labelCol: { span: 5 },
        wrapperCol: { span: 16 },
      }
    },
    created() {
      // this.handleChangeCheckCode();
      var userAll =  JSON.parse(localStorage.getItem('userAll'))
      if(userAll !== null){
        if(userAll.password){
          this.model.username= userAll.username
          this.model.password= userAll.password
        }
      }
    //  console.log("userAll",userAll)
    },
    methods:{
      ...mapActions(['Login','userLimitList']),
      ...mapGetters(['userInfo']),
      openPass(){
        this.eysShow = !this.eysShow
      },
      /**刷新验证码*/
      handleChangeCheckCode(){
        this.currdatetime = new Date().getTime();
        this.model.inputCode = ''
        getAction(`/sys/randomImage/${this.currdatetime}`).then(res=>{
          if(res.success){
            this.randCodeImage = res.result
            this.requestCodeSuccess=true
          }else{
            this.$message.error(res.message)
            this.requestCodeSuccess=false
          }
        }).catch(()=>{
          this.requestCodeSuccess=false
        })
      },
      // 判断登录类型
      handleUsernameOrEmail (rule, value, callback) {
        const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        if (regex.test(value)) {
          this.loginType = 0
        } else {
          this.loginType = 1
        }
        callback()
      },
      /**
       * 验证字段
       * @param arr
       * @param callback
       */
      validateFields(arr, callback){
        let promiseArray = []
        for(let item of arr){
          let p = new Promise((resolve, reject) => {
            this.$refs['form'].validateField(item, (err)=>{
              if(!err){
                resolve();
              }else{
                reject(err);
              }
            })
          });
          promiseArray.push(p)
        }
        Promise.all(promiseArray).then(()=>{
          callback()
        }).catch(err=>{
          callback(err)
        })
      },
      acceptUsername(username){
        this.model['username'] = username
      },
      //账号密码登录
      handleLogin(rememberMe){
        this.validateFields([ 'username', 'password' ], (err)=>{
          if(!err){
            var code;
            try{
              code = JSON.parse(sessionStorage.getItem('RECOMMEND_CODE') || "")
            }catch{
              code = ''
            }
            let loginParams = {
              username: this.model.username,
              password: this.model.password,
              // captcha: this.model.inputCode,
              checkKey: this.currdatetime,
              remember_me: rememberMe,
              code:code
            }
            console.log("登录参数", loginParams)
            localStorage.setItem('username',JSON.stringify(loginParams.username))
            this.Login(loginParams).then((res) => {
              this.$emit('success', res.result)
              localStorage.setItem('userAll',JSON.stringify(loginParams))
              this.$store.dispatch('userLimitList', {userId:this.userInfo().id})
            }).catch((err) => {
              //update-begin-author: taoyan date:20220425 for: 登录页面，当输入验证码错误时，验证码图片要刷新一下，而不是保持旧的验证码图片不变 #41
              if(err && err.code===412){
                // this.handleChangeCheckCode();
              }
              //update-end-author: taoyan date:20220425 for: 登录页面，当输入验证码错误时，验证码图片要刷新一下，而不是保持旧的验证码图片不变 #41
              this.$emit('fail', err)
            });
          }else{
            this.$emit('validateFail')
          }
        })
      }


    }

  }
</script>

<style scoped>
.icon{
  text-align: center;
    margin: 0 0 26px 0;
    border-bottom: 2px solid white;
    padding-bottom: 30px;
    position: relative;
}
.icon::before{
  content: '';
    display: block;
    position: absolute;
    bottom: 0;
    left: calc(50% - 1px);
    width: 2px;
    height: 25px;
    background: #ffffff;
}
.icon img{
  width: 60px;
    height: 60px;
    border-radius: 50%;
}

.ant-form-item-children .iconfont{
  position: absolute;
    right: 0;
    width: 30px;
    text-align: center;
    cursor: pointer;
}
</style>